package com.qwc.blog.entity.vo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.qwc.blog.common.constant.CommonConstant;
import com.qwc.blog.entity.Classify;
import lombok.Data;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author qiuwencong
 * @Date 2022/2/16 16:53
 * @Package com.qwc.blog.entity.vo
 * @Description
 */
@Data
public class ClassifyTreeVo {
    /**
     * ID
     */
    private Integer classifyId;

    /**
     * 类名
     */
    private String name;

    /**
     * 排序
     */
    private Integer sort;

    /**
     * 状态
     */
    private String status;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 更新时间
     */
    private Date updateTime;

    /**
     * 父id
     */
    private Integer pid;

    private List<ClassifyTreeVo> children;

    public static List<ClassifyTreeVo> getTree(List<Classify> list) {
        List<ClassifyTreeVo> tree = new ArrayList<>();
        for (Classify classify : list) {
            if (CommonConstant.ROOT.equals(classify.getPid())){
                ClassifyTreeVo treeVo = new ClassifyTreeVo();
                BeanUtil.copyProperties(classify,treeVo);
                addChildren(treeVo, list);
                tree.add(treeVo);
            }
        }
        return tree;
    }

    public static void addChildren(ClassifyTreeVo vo, List<Classify> list) {
        for (Classify classify : list) {
            if (classify.getPid().equals(vo.getClassifyId())) {
                if (CollUtil.isEmpty(vo.getChildren())) {
                    vo.setChildren(new ArrayList<>());
                }
                ClassifyTreeVo nextVo = createClassifyTreeVo(classify);
                vo.getChildren().add(nextVo);
                addChildren(nextVo, list);
            }
        }
    }

    private static ClassifyTreeVo createClassifyTreeVo(Classify next) {
        ClassifyTreeVo vo = new ClassifyTreeVo();
        BeanUtil.copyProperties(next,vo);
        return vo;
    }


}
